package com.example.picture_sharing_system;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.constraintlayout.solver.state.State;
import androidx.fragment.app.Fragment;

import android.os.Looper;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import utils.Constants;


public class ConfigFragment extends Fragment {

    private RelativeLayout sign_out;
    private RelativeLayout remove_account;
    private RelativeLayout change_pwd;
    private TextView tv_username;
    private String username;
    private RelativeLayout person_message;
    private int flag = 1;
    private int userid;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_config, container, false);
        initData(rootView);
        return rootView;
    }

    public void initData(View view) {


        userid = getActivity().getIntent().getIntExtra("userid", 0);

        person_message = view.findViewById(R.id.person_message);
        change_pwd = view.findViewById(R.id.change_pwd);
        tv_username = view.findViewById(R.id.username);
        sign_out = view.findViewById(R.id.sign_out);
        remove_account = view.findViewById(R.id.remove_account);

        person_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                intent.putExtra("userid", userid);
                startActivity(intent);
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url(Constants.SERVER_URL + "/get/username?userid=" + userid)
                        .get().build();
                try {
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            final String body = response.body().string();
                            if (!(getActivity().isFinishing()) && isAdded()) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tv_username.setText(body);
                                    }
                                });
                            }
                        }
                    });
                } catch (NetworkOnMainThreadException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();


        tv_username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = tv_username.getText().toString();

                View edit_username_view = LayoutInflater.from(getContext())
                        .inflate(R.layout.dialog_edit_username, null);
                EditText edit_username = edit_username_view.findViewById(R.id.new_username);

                AlertDialog dialog = new AlertDialog.Builder(getContext())
                        .setTitle("修改用户名")
                        .setView(edit_username_view)
                        .setPositiveButton("确认修改", null).create();
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (edit_username.getText().toString().length() <= 0) {
                            Toast.makeText(getContext(), "输入不能为空", Toast.LENGTH_SHORT).show();
                            flag = 0;
                        } else if (edit_username.getText().toString().equals(username)) {
                            Toast.makeText(getContext(), "与原用户名一致", Toast.LENGTH_SHORT).show();
                            flag = 0;
                        } else {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    String urlParams
                                            = "?old_username=" + username
                                            + "&new_username=" + edit_username.getText().toString();
                                    Request request = new Request.Builder()
                                            .url(Constants.EDIT_USERNAME_URL + urlParams)
                                            .get().build();
                                    try {
                                        OkHttpClient client = new OkHttpClient();
                                        client.newCall(request).enqueue(new Callback() {
                                            @Override
                                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                                e.printStackTrace();
                                            }

                                            @Override
                                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                                final String body = response.body().string();

                                                if (body.equals("修改成功")) {
                                                    Looper.prepare();
                                                    Toast.makeText(getContext(), body, Toast.LENGTH_SHORT).show();
                                                    Looper.loop();
                                                }
                                            }
                                        });
                                    } catch (NetworkOnMainThreadException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }).start();
                        }
                        Log.d("TAG", "onClick: " + flag);

                        if (flag == 1) {
                            dialog.hide();
                            dialog.dismiss();
                            tv_username.setText(edit_username.getText().toString());
                            username = edit_username.getText().toString();
                        }
                    }

                });


            }
        });
        remove_account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = tv_username.getText().toString();

                View remove_account_view = LayoutInflater.from(getContext())
                        .inflate(R.layout.remove_account_view, null);
                EditText password = remove_account_view.findViewById(R.id.password);

                AlertDialog dialog = new AlertDialog.Builder(getContext())
                        .setTitle("确认密码")
                        .setView(remove_account_view)
                        .setPositiveButton("注销", null).create();
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (password.getText().toString().length() <= 0) {
                            Toast.makeText(getContext(), "输入不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    String urlParams
                                            = "?username=" + username
                                            + "&password=" + password.getText().toString();
                                    Request request = new Request.Builder()
                                            .url(Constants.REMOVE_ACCOUNT_URL + urlParams)
                                            .get().build();
                                    try {
                                        OkHttpClient client = new OkHttpClient();
                                        client.newCall(request).enqueue(new Callback() {
                                            @Override
                                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                                e.printStackTrace();
                                            }

                                            @Override
                                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                                final String body = response.body().string();

                                                getActivity().runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (body.equals("密码错误")) {
                                                            Toast.makeText(getContext(), body, Toast.LENGTH_SHORT).show();
                                                        } else if (body.equals("success")) {
                                                            dialog.hide();
                                                            dialog.dismiss();
                                                            Toast.makeText(getContext(), "成功注销", Toast.LENGTH_SHORT).show();
                                                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                                                            startActivity(intent);
                                                            getActivity().finish();
                                                        }
                                                    }
                                                });
                                            }
                                        });
                                    } catch (NetworkOnMainThreadException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }).start();
                        }

                    }
                });
            }
        });


        sign_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(getContext())
                        .setTitle("提示")
                        .setMessage("确认要退出吗？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                startActivity(intent);
                                getActivity().finish();
                            }
                        }).show();
            }
        });


        change_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View alter_password_view = LayoutInflater.from(getContext())
                        .inflate(R.layout.alter_password_view, null);
                EditText new_pwd = alter_password_view.findViewById(R.id.new_pwd);
                EditText confirm_pwd = alter_password_view.findViewById(R.id.confirm_pwd);

                AlertDialog dialog = new AlertDialog.Builder(getContext())
                        .setTitle("修改密码")
                        .setView(alter_password_view)
                        .setPositiveButton("确定", null).create();

                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (confirm_pwd.getText().toString().length() <= 0) {
                            Toast.makeText(getContext(), "输入不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (new_pwd.getText().toString().length() <= 0) {
                            Toast.makeText(getContext(), "输入不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    String n_pwd
                                            = "?userid=" + userid
                                            + "&password=" + confirm_pwd.getText().toString()
                                            + "&newPwd=" + new_pwd.getText().toString();
                                    Request request = new Request.Builder()
                                            .url(Constants.EDIT_PASSWORD_URL + n_pwd)
                                            .get().build();
                                    try {
                                        OkHttpClient client = new OkHttpClient();
                                        client.newCall(request).enqueue(new Callback() {
                                            @Override
                                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                                e.printStackTrace();
                                            }

                                            @Override
                                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                                final String body = response.body().string();

                                                getActivity().runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (body.equals("密码错误")) {

                                                            Toast.makeText(getContext(), body, Toast.LENGTH_SHORT).show();

                                                        } else if (body.equals("新密码不能于原密码一致")) {

                                                            Toast.makeText(getContext(), body, Toast.LENGTH_SHORT).show();


                                                        } else {

                                                            dialog.hide();
                                                            dialog.dismiss();
                                                            Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();
                                                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                                                            startActivity(intent);
                                                            getActivity().finish();
                                                        }
                                                    }
                                                });
                                            }
                                        });
                                    } catch (NetworkOnMainThreadException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                        }

                    }
                });
            }
        });

    }


}